package com.css.apps.base.org.action;

import com.css.apps.base.common.Constants;
import com.css.apps.base.org.model.SOrg;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.query.QueryCache;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

@SuppressWarnings("serial")
public class GetOrg extends AdminAction {
	
	private static Log log = LogFactory.getLog(GetOrg.class);
	private String uuid, parentId;
	private int orgLevel;
	private SOrg item;
	private String isBranch = "N";

	@Override
	protected String adminGo() {
		try {
			Tree tree = new TreeCache(SOrg.class);
			if (StringHelper.isNotEmpty(uuid)) {
				item = QueryCache.get(SOrg.class, uuid);
			} else {
				if (StringHelper.isEmpty(parentId)) {
					parentId = "Y".equalsIgnoreCase(isBranch)?tree.getTreeNode(sUser.getOrganId()).getNodeId() : tree.getRoot().get(0).getNodeId();
				}
				List<TreeNode> brotherNodes = tree.getTreeNode(parentId).getChildren();
				int orderNum = 0;
				if (brotherNodes != null && brotherNodes.size() != 0) {
					for (TreeNode node : brotherNodes) {
						String nodeId = node.getNodeId();
						SOrg org = QueryCache.get(SOrg.class, nodeId);
						if (org.getOrderNum() != null && orderNum < org.getOrderNum()) {
							orderNum = org.getOrderNum();
						}
					}
				}
				orderNum++;
				item = new SOrg();
				item.setOrgType("2"); // 部门
				item.setOrderNum(orderNum);
				item.setParentId(parentId);
				item.setOrgLevel(orgLevel);
				item.setOpenFlag(Constants.YES);
			}
			return Action.SUCCESS;
		} catch (Exception ex) {
			setMessage(Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public SOrg getItem() {
		return item;
	}

	public void setItem(SOrg item) {
		this.item = item;
	}

	public int getOrgLevel() {
		return orgLevel;
	}

	public void setOrgLevel(int orgLevel) {
		this.orgLevel = orgLevel;
	}

	public String getIsBranch() {
		return isBranch;
	}

	public void setIsBranch(String isBranch) {
		this.isBranch = isBranch;
	}
}
